package com.robotserver.orders.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.jd.open.api.sdk.domain.kplmd.local.response.orderid.T;
import com.robotserver.orders.common.DateFormatUtil;
import com.robotserver.orders.common.DateUtil;
import com.robotserver.orders.common.Math;
import com.robotserver.orders.common.Tools;
import com.robotserver.orders.entity.AlimmTokens;
import com.robotserver.orders.entity.TbOrders;
import com.robotserver.orders.enums.BizStatus;
import com.robotserver.orders.mapper.SysSettingMapper;
import com.robotserver.orders.mapper.TbOrdersMapper;
import com.robotserver.orders.param.TbOrderSyncParam;
import com.robotserver.orders.param.TbOrderSyncParamV3;
import com.robotserver.orders.service.TbOrderManualService;
import com.robotserver.orders.vo.TbkOrderTimeVO;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkScOrderDetailsGetRequest;
import com.taobao.api.response.TbkScOrderDetailsGetResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Auther: jianghan
 * @Date: 2019/12/16 20:28
 * @Description:
 */
@Service
public class TbOrderManualServiceImpl implements TbOrderManualService {

    private static Logger logger = LoggerFactory.getLogger(TbOrderManualServiceImpl.class);

    @Value("${taobao.sdk.url}")
    private String taobaoSdkUrl;
    @Autowired
    private SysSettingMapper sysSettingMapper;

    private static long pagesize = 100;
    @Autowired
    private TbOrdersMapper tbOrdersMapper;

    @Async("taskExecutor")
    @Override
    public void remotePull(TbOrderSyncParam tbOrderSyncParam) {
        String tb_appkey = sysSettingMapper.getByKey("tb_appkey");
        String tb_appsecret = sysSettingMapper.getByKey("tb_appsecret");
        TaobaoClient client = new DefaultTaobaoClient(taobaoSdkUrl, tb_appkey, tb_appsecret);

        List<TbkOrderTimeVO> tbkOrderTimeVOList = DateUtil.getTbkOrderTimeScope(tbOrderSyncParam.getBegin_time(),tbOrderSyncParam.getEnd_time());

        if (tbOrderSyncParam.getTkStatus()==null){
            for (TbkOrderTimeVO tbkOrderTimeVO:tbkOrderTimeVOList){
                syncTimeUnitOrder(tbkOrderTimeVO,tbOrderSyncParam,client,null,1l,null,null);
                try {
                    Thread.sleep(20); //线程停止20毫秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }else if (tbOrderSyncParam.getTkStatus()==1){
            // 付款
            for (TbkOrderTimeVO tbkOrderTimeVO:tbkOrderTimeVOList){
                syncTimeUnitOrder(tbkOrderTimeVO,tbOrderSyncParam,client,null,1l,12l,null);
                try {
                    Thread.sleep(20); //线程停止20毫秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }else if(tbOrderSyncParam.getTkStatus()==2){
            // 失效
            for (TbkOrderTimeVO tbkOrderTimeVO:tbkOrderTimeVOList){
                syncTimeUnitOrder(tbkOrderTimeVO,tbOrderSyncParam,client,null,1l,13l,null);
                try {
                    Thread.sleep(20); //线程停止20毫秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }else if(tbOrderSyncParam.getTkStatus()==3){
            // 结算
            for (TbkOrderTimeVO tbkOrderTimeVO:tbkOrderTimeVOList){
                syncTimeUnitOrder(tbkOrderTimeVO,tbOrderSyncParam,client,null,1l,14l,null);
                try {
                    Thread.sleep(20); //线程停止20毫秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for (TbkOrderTimeVO tbkOrderTimeVO:tbkOrderTimeVOList){
                syncTimeUnitOrder(tbkOrderTimeVO,tbOrderSyncParam,client,null,1l,3l,null);
                try {
                    Thread.sleep(20); //线程停止20毫秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        //会员订单
        if (tbOrderSyncParam.getTkStatus()==null){
            for (TbkOrderTimeVO tbkOrderTimeVO:tbkOrderTimeVOList){
                syncTimeUnitOrder(tbkOrderTimeVO,tbOrderSyncParam,client,null,1l,null,3l);
                try {
                    Thread.sleep(20); //线程停止10毫秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }else if (tbOrderSyncParam.getTkStatus()==1){
            // 付款
            for (TbkOrderTimeVO tbkOrderTimeVO:tbkOrderTimeVOList){
                syncTimeUnitOrder(tbkOrderTimeVO,tbOrderSyncParam,client,null,1l,12l,3l);
                try {
                    Thread.sleep(20); //线程停止10毫秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }else if(tbOrderSyncParam.getTkStatus()==2){
            // 失效
            for (TbkOrderTimeVO tbkOrderTimeVO:tbkOrderTimeVOList){
                syncTimeUnitOrder(tbkOrderTimeVO,tbOrderSyncParam,client,null,1l,13l,3l);
                try {
                    Thread.sleep(20); //线程停止10毫秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }else if(tbOrderSyncParam.getTkStatus()==3){
            // 结算
            for (TbkOrderTimeVO tbkOrderTimeVO:tbkOrderTimeVOList){
                syncTimeUnitOrder(tbkOrderTimeVO,tbOrderSyncParam,client,null,1l,14l,3l);
                try {
                    Thread.sleep(20); //线程停止10毫秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for (TbkOrderTimeVO tbkOrderTimeVO:tbkOrderTimeVOList){
                syncTimeUnitOrder(tbkOrderTimeVO,tbOrderSyncParam,client,null,1l,3l,3l);
                try {
                    Thread.sleep(20); //线程停止10毫秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @Override
    public void syncTimeUnitOrder(TbkOrderTimeVO tbkOrderTimeVO,TbOrderSyncParam tbOrderSyncParam, TaobaoClient client, String positionindex, Long pageNo,Long tkstatus,Long orderScene) {
        try {
            TbkScOrderDetailsGetRequest req = new TbkScOrderDetailsGetRequest();

            logger.info("------远程拉取单个联盟订单-------"+tbOrderSyncParam.getAccessToken()+"::"+tbOrderSyncParam.getUserName()+"::"+tbkOrderTimeVO.getBeginTime()+"::"+tbkOrderTimeVO.getEndTime());
            req.setQueryType(tbOrderSyncParam.getTimeType());

            if (StringUtils.isNotBlank(positionindex)){
                req.setPositionIndex(positionindex);
            }

            req.setPageSize(pagesize);
            req.setTkStatus(tkstatus);
            req.setStartTime(tbkOrderTimeVO.getBeginTime());
            req.setEndTime(tbkOrderTimeVO.getEndTime());
            req.setJumpType(1l);
            req.setPageNo(pageNo);
            req.setOrderScene(tbOrderSyncParam.getOrderScene());
            TbkScOrderDetailsGetResponse rsp = client.execute(req, tbOrderSyncParam.getAccessToken());
            // 处理入库
            if (rsp.getData()!=null){
                ordersDispose(rsp.getData().getResults(),tbOrderSyncParam);

                if (rsp.getData().getHasNext()){
                    pageNo = pageNo+1;
                    syncTimeUnitOrder(tbkOrderTimeVO,tbOrderSyncParam,client,rsp.getData().getPositionIndex(),pageNo,tkstatus,orderScene);
                }
            }
        } catch (ApiException e) {
            logger.error("");
        }
    }

    @Transactional
    @Override
    public void ordersDispose(List<TbkScOrderDetailsGetResponse.PublisherOrderDto> orders, TbOrderSyncParam tbOrderSyncParam) {
        int now = DateUtil.getNowTime();
        if (orders==null || orders.size()==0){
            return ;
        }
        for (TbkScOrderDetailsGetResponse.PublisherOrderDto order:orders){

            Date modifyTimeDate = DateFormatUtil.StringToDateFormat(order.getModifiedTime(),"yyyy-MM-dd HH:mm:ss");
            Integer modifyTime = DateUtil.getTime(modifyTimeDate);
            //支付总金额
            int alipayTotalPrice = Math.currencyFormatToF(order.getAlipayTotalPrice());
            // 查询订单是否存在
            TbOrders tbOrder = tbOrdersMapper.getByOrderNo(order.getTradeParentId(),order.getTradeId());
            if (tbOrder!=null){

                //如果淘宝状态和修改时间都不变，则不修改
                if(tbOrder.getTkStatus().intValue() == order.getTkStatus().intValue()
                        && Tools.getInteger(tbOrder.getModifiedTime()).intValue() == Tools.getInteger(modifyTime).intValue()){
                    continue;
                }

                // 修改
                tbOrder.setUpdateTime(now);
                tbOrder.setAdzoneId(order.getAdzoneId());
                tbOrder.setAdzoneName(order.getAdzoneName());
                tbOrder.setAlimamaRate(Math.strToDouble(order.getAlimamaRate()));
                tbOrder.setAlimamaShareFee(Math.currencyFormatToF(order.getAlimamaShareFee()));
                tbOrder.setAlimmUserId(String.valueOf(tbOrderSyncParam.getUserId()));
                tbOrder.setAlimmUserName(tbOrderSyncParam.getUserName());
                tbOrder.setAlipayTotalPrice(Math.currencyFormatToF(order.getAlipayTotalPrice()));
                tbOrder.setAppKey(order.getAppKey());

                //modify by 2021-03-10 18:00 by liuqi
                tbOrder.setAlscId(order.getAlscId());
                tbOrder.setAlscPid(order.getAlscPid());
                tbOrder.setLxRid(order.getLxRid());
                tbOrder.setIsLx(order.getIsLx());
                tbOrder.setMarketingType(order.getMarketingType());
                tbOrder.setModifiedTime(modifyTime);

                tbOrder.setBizStatus(getStatus(order.getTkStatus().intValue()));
                tbOrder.setClickTime(DateUtil.getStrTime(order.getClickTime()));
                tbOrder.setDepositPrice(Math.currencyFormatToF(order.getDepositPrice()));
                tbOrder.setFlowSource(order.getFlowSource());
                tbOrder.setIncomeRate(Math.strToDouble(order.getIncomeRate()));
                tbOrder.setItemCategoryName(order.getItemCategoryName());
                tbOrder.setItemId(order.getItemId());
                tbOrder.setItemImg(order.getItemImg());
                tbOrder.setItemLink(order.getItemLink());
                tbOrder.setItemNum(order.getItemNum());
                tbOrder.setItemPrice(Math.currencyFormatToF(order.getItemPrice()));
                tbOrder.setItemTitle(order.getItemTitle());

                tbOrder.setOrderType(order.getOrderType());
                tbOrder.setPayPrice(Math.currencyFormatToF(order.getPayPrice()));
                tbOrder.setPubId(order.getPubId());
                tbOrder.setPubShareFee(Math.currencyFormatToF(order.getPubShareFee()));
                tbOrder.setPubSharePreFee(Math.currencyFormatToF(order.getPubSharePreFee()));
                tbOrder.setPubShareRate(Math.strToDouble(order.getPubShareRate()));
                tbOrder.setRefundTag((int) order.getRefundTag().longValue());
                String sellerNick = order.getSellerNick();
                if(StringUtils.isNotBlank(sellerNick)){
                    tbOrder.setSellerNick(sellerNick.length() > 32? sellerNick.substring(0,30) : sellerNick);
                }
                tbOrder.setSellerShopTitle(order.getSellerShopTitle());
                tbOrder.setSiteId(order.getSiteId());
                tbOrder.setSiteName(order.getSiteName());

                if (tbOrder.getSpecialId()==null && order.getSpecialId()!=null){
                    tbOrder.setSpecialId(order.getSpecialId());
                }

                //更新渠道ID
                if (tbOrder.getRelationId() == null && order.getRelationId() !=null){
                    tbOrder.setRelationId(order.getRelationId());
                }

                tbOrder.setSubsidyRate(Math.strToDouble(order.getSubsidyRate()));
                tbOrder.setSubsidyFee(Math.currencyFormatToF(order.getSubsidyFee()));
                tbOrder.setSubsidyType(order.getSubsidyType());
                tbOrder.setTbDepositTime(DateUtil.getStrTime(order.getTbDepositTime()));
                tbOrder.setTbPaidTime(DateUtil.getStrTime(order.getTbPaidTime()));
                tbOrder.setTerminalType(order.getTerminalType());
                tbOrder.setTkCommissionFeeForMediaPlatform(Math.currencyFormatToF(order.getTkCommissionFeeForMediaPlatform()));
                tbOrder.setTkCommissionPreFeeForMediaPlatform(Math.currencyFormatToF(order.getTkCommissionPreFeeForMediaPlatform()));
                tbOrder.setTkCommissionRateForMediaPlatform(Math.strToDouble(order.getTkCommissionRateForMediaPlatform()));
                tbOrder.setTkCreateTime(DateUtil.getStrTime(order.getTkCreateTime()));
                tbOrder.setTkEarningTime(DateUtil.getStrTime(order.getTkEarningTime()));
                tbOrder.setTkOrderRole(order.getTkOrderRole());
                tbOrder.setTkPaidTime(DateUtil.getStrTime(order.getTkPaidTime()));
                tbOrder.setTradeId(order.getTradeId());
                tbOrder.setTradeParentId(order.getTradeParentId());
                tbOrder.setTkTotalRate(Math.strToDouble(order.getTkTotalRate()));
                tbOrder.setTkStatus((int)order.getTkStatus().longValue());
                tbOrder.setTotalCommissionRate(Math.strToDouble(order.getTotalCommissionRate()));
                tbOrder.setTotalCommissionFee(Math.currencyFormatToF(order.getTotalCommissionFee()));
                tbOrder.setTkDepositTime(DateUtil.getStrTime(order.getTkDepositTime()));
                tbOrder.setPid("mm_"+order.getPubId()+"_"+order.getSiteId()+"_"+order.getAdzoneId());
                tbOrdersMapper.update(tbOrder);
            }else {
                // 添加
                logger.info("add tb pay order:parentId: {},childId: {},tkstatus:{}",new Object[]{order.getTradeParentId(),order.getTradeId(),order.getTkStatus()});
                TbOrders newOrder = new TbOrders();
                newOrder.setId(IdWorker.getId());
                newOrder.setCreateTime(now);
                newOrder.setUpdateTime(now);
                newOrder.setAdzoneId(order.getAdzoneId());
                newOrder.setAdzoneName(order.getAdzoneName());
                newOrder.setAlimamaRate(Math.strToDouble(order.getAlimamaRate()));
                newOrder.setAlimamaShareFee(Math.currencyFormatToF(order.getAlimamaShareFee()));
                newOrder.setAlimmUserId(String.valueOf(tbOrderSyncParam.getUserId()));
                newOrder.setAlimmUserName(tbOrderSyncParam.getUserName());
                newOrder.setAlipayTotalPrice(Math.currencyFormatToF(order.getAlipayTotalPrice()));
                newOrder.setAppKey(order.getAppKey());

                //modify by 2021-03-10 18:00 by liuqi
                newOrder.setAlscId(order.getAlscId());
                newOrder.setAlscPid(order.getAlscPid());
                newOrder.setLxRid(order.getLxRid());
                newOrder.setIsLx(order.getIsLx());
                newOrder.setMarketingType(order.getMarketingType());
                newOrder.setModifiedTime(modifyTime);

                newOrder.setBizStatus(getStatus(order.getTkStatus().intValue()));
                newOrder.setClickTime(DateUtil.getStrTime(order.getClickTime()));
                newOrder.setDepositPrice(Math.currencyFormatToF(order.getDepositPrice()));
                newOrder.setFlowSource(order.getFlowSource());
                newOrder.setIncomeRate(Math.strToDouble(order.getIncomeRate()));
                newOrder.setItemCategoryName(order.getItemCategoryName());
                newOrder.setItemId(order.getItemId());
                newOrder.setItemImg(order.getItemImg());
                newOrder.setItemLink(order.getItemLink());
                newOrder.setItemNum(order.getItemNum());
                newOrder.setItemPrice(Math.currencyFormatToF(order.getItemPrice()));
                newOrder.setItemTitle(order.getItemTitle());

                newOrder.setOrderType(order.getOrderType());
                newOrder.setPayPrice(Math.currencyFormatToF(order.getPayPrice()));
                newOrder.setPubId(order.getPubId());
                newOrder.setPubShareFee(Math.currencyFormatToF(order.getPubShareFee()));
                newOrder.setPubSharePreFee(Math.currencyFormatToF(order.getPubSharePreFee()));
                newOrder.setPubShareRate(Math.strToDouble(order.getPubShareRate()));
                newOrder.setRefundTag((int) order.getRefundTag().longValue());
                newOrder.setRelationId(order.getRelationId());
                newOrder.setSellerNick(order.getSellerNick());
                newOrder.setSellerShopTitle(order.getSellerShopTitle());
                newOrder.setSiteId(order.getSiteId());
                newOrder.setSiteName(order.getSiteName());
                newOrder.setSpecialId(order.getSpecialId());
                newOrder.setSubsidyRate(Math.strToDouble(order.getSubsidyRate()));
                newOrder.setSubsidyFee(Math.currencyFormatToF(order.getSubsidyFee()));
                newOrder.setSubsidyType(order.getSubsidyType());
                newOrder.setTbDepositTime(DateUtil.getStrTime(order.getTbDepositTime()));
                newOrder.setTbPaidTime(DateUtil.getStrTime(order.getTbPaidTime()));
                newOrder.setTerminalType(order.getTerminalType());
                newOrder.setTkCommissionFeeForMediaPlatform(Math.currencyFormatToF(order.getTkCommissionFeeForMediaPlatform()));
                newOrder.setTkCommissionPreFeeForMediaPlatform(Math.currencyFormatToF(order.getTkCommissionPreFeeForMediaPlatform()));
                newOrder.setTkCommissionRateForMediaPlatform(Math.strToDouble(order.getTkCommissionRateForMediaPlatform()));
                newOrder.setTkCreateTime(DateUtil.getStrTime(order.getTkCreateTime()));
                newOrder.setTkEarningTime(DateUtil.getStrTime(order.getTkEarningTime()));
                newOrder.setTkOrderRole(order.getTkOrderRole());
                newOrder.setTkPaidTime(DateUtil.getStrTime(order.getTkPaidTime()));
                newOrder.setTradeId(order.getTradeId());
                newOrder.setTradeParentId(order.getTradeParentId());
                newOrder.setTkTotalRate(Math.strToDouble(order.getTkTotalRate()));
                newOrder.setTkStatus((int)order.getTkStatus().longValue());
                newOrder.setTotalCommissionRate(Math.strToDouble(order.getTotalCommissionRate()));
                newOrder.setTotalCommissionFee(Math.currencyFormatToF(order.getTotalCommissionFee()));
                newOrder.setTkDepositTime(DateUtil.getStrTime(order.getTkDepositTime()));
                newOrder.setPid("mm_"+order.getPubId()+"_"+order.getSiteId()+"_"+order.getAdzoneId());
                tbOrdersMapper.add(newOrder);
            }
        }
    }

    private int getStatus(int orderStatus){
        switch (orderStatus){
            case 12:
                return 0;
            case 13:
                return 2;
            case 14:
                return 1;
            case 3:
                return 1;
        }
        return 0;
    }

    @Async("taskExecutor")
    @Override
    public void remotePullV3(TbOrderSyncParamV3 tbOrderSyncParamV3) {

        //判断是否订单号为空，如果不为空，则先修改数据库此订单的最新修改时间
        if(StringUtils.isNotBlank(tbOrderSyncParamV3.getChildOrderNo()) && StringUtils.isNotBlank(tbOrderSyncParamV3.getParentOrderNo()) ){
            tbOrdersMapper.updateUpdateTime(tbOrderSyncParamV3.getParentOrderNo(),tbOrderSyncParamV3.getChildOrderNo());
        }

        //从新拉取
        TaobaoClient client = null;
        if(tbOrderSyncParamV3.getTurnlink() != null && tbOrderSyncParamV3.getTurnlink().intValue() == 1){
            String tb_appkey_dg = sysSettingMapper.getByKey("tb_appkey_dg");
            String tb_appsecret_dg = sysSettingMapper.getByKey("tb_appsecret_dg");
            client = new DefaultTaobaoClient(taobaoSdkUrl, tb_appkey_dg, tb_appsecret_dg);
        }else{
            String tb_appkey = sysSettingMapper.getByKey("tb_appkey");
            String tb_appsecret = sysSettingMapper.getByKey("tb_appsecret");
            client = new DefaultTaobaoClient(taobaoSdkUrl, tb_appkey, tb_appsecret);
        }

        if(client != null){
            TbOrderSyncParam tbOrderSyncParam = new TbOrderSyncParam();
            tbOrderSyncParam.setAccessToken(tbOrderSyncParamV3.getAccessToken());
            tbOrderSyncParam.setUserId(tbOrderSyncParamV3.getUserId());
            tbOrderSyncParam.setUserName(tbOrderSyncParamV3.getUserName());
            tbOrderSyncParam.setOrderScene(tbOrderSyncParamV3.getOrderScene());
            tbOrderSyncParam.setTimeType(tbOrderSyncParamV3.getQueryType());

            List<TbkOrderTimeVO> tbkOrderTimeVOList = DateUtil.getTbkOrderTimeScope(tbOrderSyncParamV3.getBeginTime(), tbOrderSyncParamV3.getEndTime());
            if(tbkOrderTimeVOList != null && tbkOrderTimeVOList.size() > 0){
                for (TbkOrderTimeVO tbkOrderTimeVO : tbkOrderTimeVOList){
                    syncTimeUnitOrder(tbkOrderTimeVO, tbOrderSyncParam, client,null,1l,null,null);
                }
            }
        }

    }
}
